

class ReceivingTicketsController < ApplicationController
  before_action :set_receiving_ticket, only: [:show, :edit, :update, :destroy]

  # GET /receiving_tickets
  # GET /receiving_tickets.json
  def index
    #@receiving_tickets = ReceivingTicket.all
    @receiving_tickets = ReceivingTicket.paginate(:page => params[:page], :per_page => 8)
    respond_to do |format|
      format.html
      format.json
      format.pdf do
        encabezados = ["Numero RT","Item","Descripcion","Cantidad","Fecha Recepcion"]
        @rts_reporte = RtDetalle.rts_reporte
        generar_reporte("index",@rts_reporte,:encabezados =>encabezados, :titulo => "Reporte RT'S",:columnas_size => 100)
      end
    end
  end

  # GET /receiving_tickets/1
  # GET /receiving_tickets/1.json
  def show
  end

  # GET /receiving_tickets/new
  def new
    @receiving_ticket = ReceivingTicket.new
    @receiving_ticket.build_rt_proveedor
    @receiving_ticket.build_rt_transportista
    @receiving_ticket.build_rt_mercancia
    @receiving_ticket.build_reexpedicion
    
    objetos_combos
  end

  # GET /receiving_tickets/1/edit
  def edit
    @receiving_ticket.build_rt_proveedor unless @receiving_ticket.rt_proveedor
    @receiving_ticket.build_rt_transportista unless @receiving_ticket.rt_transportista
    @receiving_ticket.build_rt_mercancia unless @receiving_ticket.rt_mercancia
    @receiving_ticket.build_reexpedicion unless @receiving_ticket.reexpedicion
    @tipos_entrada = TipoEntrada.all
    @destinos = Pais.all
    @clientes = Cliente.all
    @proveedores = Proveedor.all
    @transportistas = Transportista.all
    @empleados = Empleado.all
    @unidades_medida = UnidadMedida.all
    @estatus_mercancias = EstatusMercancia.all
    @incidencias = Incidencia.all
    @cliente= current_usuario.cliente
    @vias = Transportista.all
    @tipos_envio = TipoEnvio.all
    @ordenes_compra = current_usuario.ordenes_compra
    @items = Item.all
  end

  # POST /receiving_tickets
  # POST /receiving_tickets.json
  def create
    @receiving_ticket = ReceivingTicket.new(receiving_ticket_params)
    @ordenes_ids = params[:ordenes_ids]
    agregar_ordenes_compra

    respond_to do |format|
      if @receiving_ticket.save
        format.html { redirect_to detalle_rt_path(@receiving_ticket), notice: 'Receiving ticket was successfully created.' }
        format.json { render action: 'show', status: :created, location: @receiving_ticket }
      else
        objetos_combos
        format.html { render action: 'new'}
        format.json { render json: @receiving_ticket.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /receiving_tickets/1
  # PATCH/PUT /receiving_tickets/1.json
  def update
    respond_to do |format|
      if @receiving_ticket.update(receiving_ticket_params)
        format.html { redirect_to detalle_rt_path(@receiving_ticket), notice: 'Receiving ticket was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @receiving_ticket.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /receiving_tickets/1
  # DELETE /receiving_tickets/1.json
  def destroy
    @receiving_ticket.destroy
    respond_to do |format|
      format.html { redirect_to receiving_tickets_url }
      format.json { head :no_content }
    end
  end
  
  def seleccionar_cliente
    
    @accion = params[:accion]
    @clientes = Cliente.all
  end
  
  def seleccionar_ordenes
    @ordenes_compra = current_usuario.ordenes_compra
  end
  
  def ordenes_rt
    
  end
  
  def cliente_rt
    redirect_to :action=> params[:accion] , :IdCliente => params[:cliente_rt][:IdCliente]
  end
  
  def agregar_proveedor
    @proveedor = Proveedor.new
    @giros = GiroEmpresa.all
  end
  
  
  def detalle_rt
    @receiving_ticket = ReceivingTicket.find(params[:id])
    @detalle_rt = RtDetalle.new
    @paises = Pais.all
    @unidades_medida = UnidadMedida.all
    @proveedores = Proveedor.all
    @items = Item.all
    @mostrar_IdRTProveedor = false
    # Hay que obtener este ID, 
    # sino hay ningun item en las ordenes de compra 
    # ReceivingTicket.last.IdRTProveedor
    cantidad_items_ordenes_Compra = 0
    @receiving_ticket.ordenes.each do |orden|
      if orden.detalles_orden_compra.size >= 0
        mostrar_IdRTProveedor = true
      end       
    end
    #@mostrar_IdRTProveedor = true

    
    #IdRTProveedor
  end

  def guardar_detalle_rt
      @detalle_rt = RtDetalle.find_or_initialize_by(rt_detalle_params)
      
      respond_to do |format|
        if @detalle_rt.save
          format.js
          format.html {redirect_to detalle_rt_path(@detalle_rt.receiving_ticket)}
        else
          format.js
          format.html {render action: 'detalle_rt'}
        end
      end  
  end
  
  def get_detalle_rt
    @detalle_rt = RtDetalle.find(params[:id_detalle])
  end
  
  def eliminar_detalle_rt
    @detalle_rt = RtDetalle.find(params[:id])
    @detalle_rt.destroy
    respond_to do |format|
      format.html { redirect_to detalle_rt_path(@detalle_rt.receiving_ticket_id) }
      format.json { head :no_content }
      format.js
    end
  end
  
  
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_receiving_ticket
      @receiving_ticket = ReceivingTicket.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def receiving_ticket_params
      params.require(:receiving_ticket).permit(:Numero, :IdTipoEntrada, :ConsecCliente, :IdDestino, 
        :FechaRecepcion, :Hora, :IdCliente, :IdRTProveedor, :IdRTTransportista, :IdRTMercancia, 
        :IdRTReexpedicion, ordenes_compra_rt_attributes: [:id,:orden_id], 
        rt_proveedor_attributes: [:IdProveedor, :OrdenCompra, :PackingList, :Facturas, :ValTotEmbarque, :OtrosDocumentos],
        rt_oc_proveedores_attributes: [:receiving_ticket_id, :proveedor_id, :factura, :orden_compra_id],
        rt_oc_proveedores: [:receiving_ticket_id, :proveedor_id, :factura, :orden_compra_id],
        rt_transportista_attributes: [:IdTransportista, :NoCaja, :IdFormaPago, :BolNo, :NoUnidad, :Monto],
        rt_mercancia_attributes: [:producto_id,:empaque,:operador,:Recibio, :TotalPallets, :IdUnidadMedida, :IdStatus, :Capturado, :BultosPallet, :Bultos, :IdIncidencia, :DetIncidencia],
        reexpedicion_attributes: [:Via, :Destino, :Direccion, :Estado, :Telefono, :TipoEnvio, :NoCuenta, :Ciudad, :CodigoPostal])
    end
    
   def rt_detalle_params
      params.require(:rt_detalle).permit(:receiving_ticket_id, :item_id, :proveedor_id, :factura, :partida, :hoja, :descripcion, :fraccion_arancelaria, 
        :incidencia, :origen_id, :production, :expiration, :lote, :cantidad, :unidad_medida_id, :cantidad_por_caja, :unidad_medida_llegada_id, 
        :total_cajas, :total_piezas, :nom_etiquetado, :etiquetado, :tot_etiquetas, :numero_pallets, :localizacion,:det_orden_compra_id,
      :libras, :kilos, :total_kilos, :total_libras)
    end
    
    def agregar_ordenes_compra
#      ordenes = params[:ordenes_ids]

      unless @ordenes_ids.nil?
        @receiving_ticket.ordenes_compra_rt.destroy_all
        @ordenes_ids.each do |orden_id|
          orden_rt = @receiving_ticket.ordenes_compra_rt.build
          orden_rt.orden_id = orden_id
        end
      end
    end
    
    def objetos_combos
        @tipos_entrada = TipoEntrada.all
        @destinos = Pais.all
        @clientes = Cliente.all
        @proveedores = Proveedor.all
        @transportistas = Transportista.all
        @empleados = Empleado.all
        @unidades_medida = UnidadMedida.all
        @estatus_mercancias = EstatusMercancia.all
        @incidencias = Incidencia.all
        @cliente= current_usuario.cliente
        @vias = Transportista.all
        @tipos_envio = TipoEnvio.all
        @ordenes_compra = current_usuario.ordenes_compra
        @receiving_ticket.ordenes_compra_rt.build
        @receiving_ticket.rt_oc_proveedores.build
        @items = Item.all
    end
end
